<template>
  <div>
    <div
      v-if="isVisible"
      class="modal"
      :class="{ fullscreen: isFullscreen }"
      ref="modal"
      @mousedown="startDrag"
      @touchstart="startDrag"
    >
      <div class="modal-header" v-if="!isFullscreen">
        <div>倒计时</div>
        <div class="icon_r">
          <div @click.stop="toggleFullscreen" style="cursor: pointer !important">
            <img src="@/assets/images/fullscreenIcon.png"/>
          </div>
          <div @click.stop="close"  class="closeIcon" style="cursor: pointer !important">
            <img src="@/assets/images/clock_close.png"/>
          </div>
        </div>
      </div>
      <div v-else class="fullscreen_btn" @click.stop="toggleFullscreen" style="cursor: pointer !important">
        <img src="@/assets/images/close_fullScreen.png"/>
        <div>进入浮窗</div>
      </div>
      <div class="modal-body" :style="isFullscreen ? {zoom: 2, marginTop: '8vh'} : {}">
        <div v-if="type === 1">
          <TimePicker @startClock="startCountdown"></TimePicker>
        </div>
        <div class="test-clock-container" v-if="type === 2">
          <div class="clockText">倒计时结束</div>
          <div class="clock-container">
            <flip-item :total="2" :current="timeArr[0]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
            <flip-item :total="9" :current="timeArr[1]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
            <div class="colon" :class="countdown <= 180 ? 'danger-color' : ''"></div>
            <flip-item :total="5" :current="timeArr[2]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
            <flip-item :total="9" :current="timeArr[3]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
            <div class="colon" :class="countdown <= 180 ? 'danger-color' : ''"></div>
            <flip-item :total="5" :current="timeArr[4]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
            <flip-item :total="9" :current="timeArr[5]" :innColor="countdown <= 180 ? '#E5424B' : '#EEA74C'"/>
          </div>
          <div class="btn-container">
            <div class="endBtn" @click="endCountdown">结束</div>
            <div :class="isEnd?'disabled pauseBtn':'pauseBtn'" @click="pauseCountdown">{{isPaused ? '继续' : '暂停'}}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import FlipItem from '@/components/FilpClock/FilpItem.vue'
import TimePicker from '@/components/TimePicker.vue'
import { getTimeArrForCountdown } from '@/components/FilpClock/utils.js'
export default {
  name: 'CustomModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isVisible: this.visible,
      isFullscreen: false,
      isDragging: false,
      startX: 0,
      startY: 0,
      startLeft: 0,
      startTop: 0,
      countdown: 0, // 倒计时的秒数
      timeArr: getTimeArrForCountdown(this.countdown),
      timer: null,
      hours: Array.from({ length: 24 }, (_, i) => i),  // 时：0 - 23
      minutes: Array.from({ length: 60 }, (_, i) => i), // 分：0 - 59
      seconds: Array.from({ length: 60 }, (_, i) => i), // 秒：0 - 59
      selectedHour: 0,
      selectedMinute: 0,
      selectedSecond: 0,
      type: 1,
      isPaused: false,
      isEnd: false,
    }
  },
  components: {
    FlipItem,
    TimePicker
  },
  beforeDestroy() {
    this.stopTimer()
    document.removeEventListener('mouseup', this.stopDrag);
    document.removeEventListener('touchend', this.stopDrag);
  },
  watch: {
    visible(val) {
      this.isVisible = val
      if(this.isVisible){
        this.centerModal() // 显示时居中
      }
    }
  },
  methods: {
    close() {
      this.stopTimer();
      this.type = 1
      this.isVisible = false
      this.$store.dispatch('changeCustomModalVisible', false)
      // this.$emit('update:visible', false)
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      const modal = this.$refs.modal
      if (this.isFullscreen) {
        modal.style.top = '0'
        modal.style.left = '0'
        modal.style.transform = 'translate(0, 0)'
      } else {
        modal.style.top = '50%'
        modal.style.left = '50%'
        modal.style.transform = 'translate(-50%, -50%)'
      }

    },
    centerModal() {
      this.$nextTick(() => {
        const modal = this.$refs.modal
        modal.style.top = '50%'
        modal.style.left = '50%'
        modal.style.transform = 'translate(-50%, -50%)'
      })
    },
    startDrag(event) {
      if (this.isFullscreen) return // 全屏状态下不允许拖动
      this.isDragging = true
      const rect = this.$refs.modal.getBoundingClientRect()
      if(event.type === 'mousedown'){
        this.startX = event.clientX - rect.left
        this.startY = event.clientY - rect.top
        document.addEventListener('mousemove', this.onDrag)
        document.addEventListener('mouseup', this.stopDrag)
      }else if(event.type === "touchstart"){
        const touch = event.touches[0];
        this.startX = touch.clientX - rect.left
        this.startY = touch.clientY - rect.top
        document.addEventListener('touchmove', this.onDrag,{passive: true})
        document.addEventListener('touchend', this.stopDrag)
      }
    },
    onDrag(event) {
      if (!this.isDragging) return;

      let newLeft, newTop;
      if (event.type === "mousemove") {
        newLeft = event.clientX - this.startX
        newTop = event.clientY - this.startY
      } else if (event.type === "touchmove") {
        const touch = event.touches[0];
        newLeft = touch.clientX - this.startX;
        newTop = touch.clientY - this.startY;

      }
      const modalWidth = this.$refs.modal.offsetWidth
      const modalHeight = this.$refs.modal.offsetHeight
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight

      // 确保弹窗不会移出屏幕外
      if (newLeft < 0) newLeft = 0
      if (newTop < 0) newTop = 0
      if (newLeft + modalWidth > windowWidth) newLeft = windowWidth - modalWidth
      if (newTop + modalHeight > windowHeight) newTop = windowHeight - modalHeight
      this.$refs.modal.style.left = `${newLeft}px`
      this.$refs.modal.style.top = `${newTop}px`
      this.$refs.modal.style.transform = 'translate(0, 0)' // 清掉先前的transform，以直接设置位置
    },
    stopDrag() {
      this.isDragging = false
      document.removeEventListener('mousemove', this.onDrag)
      document.removeEventListener('mouseup', this.stopDrag)
      document.removeEventListener('touchmove', this.onDrag);
      document.removeEventListener('touchend', this.stopDrag);
    },
    startTimer() {
      this.countdown = this.getTimeInFuture(this.selectedHour, this.selectedMinute, this.selectedSecond)
      this.timeArr = getTimeArrForCountdown(this.countdown)
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
          this.timeArr = getTimeArrForCountdown(this.countdown)
        } else {
          this.stopTimer()
        }
      }, 1000)
    },
    stopTimer() {
      this.selectedHour=0;
      this.selectedMinute=0;
      this.selectedSecond=0;
      this.countdown = 0;
      this.timeArr = [0,0,0,0,0,0];
      clearInterval(this.timer)
    },
    startCountdown(data) {
      this.type = 2
      this.selectedHour = data.hour
      this.selectedMinute = data.minute
      this.selectedSecond = data.second
      this.startTimer()
    },
    getTimeInFuture(hours, minutes, seconds) {
      return (hours * 3600) + (minutes * 60) + seconds
    },
    onScroll(column) {
      const columnRef = this.$refs[`${column}Column`];
      const itemHeight = 40; // 每项的高度
      const centerPosition = columnRef.scrollTop + columnRef.clientHeight / 2;
      const index = Math.floor(centerPosition / itemHeight);
      // 计算显示在中间的项目索引
      if (column === 'hours') {
        this.selectedHour = this.hours[index];
        this.adjustScroll('hours', index, itemHeight);
      } else if (column === 'minutes') {
        this.selectedMinute = this.minutes[index];
        this.adjustScroll('minutes', index, itemHeight);
      } else if (column === 'seconds') {
        this.selectedSecond = this.seconds[index];
        this.adjustScroll('seconds', index, itemHeight);
      }

    },
    adjustScroll(column, index, itemHeight) {
      const columnRef = this.$refs[`${column}Column`];
      // 计算目标的 scrollTop，使选中项居中
      columnRef.scrollTop = (index * itemHeight) - (columnRef.clientHeight / 2) + (itemHeight / 2);
    },
    // 结束倒计时
    endCountdown(){
      this.isEnd=true
      this.stopTimer()
    },
    // 暂停倒计时
    pauseCountdown(){
      this.isPaused = !this.isPaused
      if(this.isPaused){
        clearInterval(this.timer)
      }else{
        this.timeArr = getTimeArrForCountdown(this.countdown)
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--
            this.timeArr = getTimeArrForCountdown(this.countdown)
          } else {
            this.stopTimer()
          }
        }, 1000)
      }
    },
  }
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 292px;
  border-radius: 4px 4px 0 0;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 1001;
  cursor: move; /* 鼠标指针样式 */
  user-select: none; /* 禁止文本被选中 */
  touch-action: none;

}

.modal.fullscreen {
  top: 0;
  left: 0;
  transform: translate(0, 0);
  width: 100%;
  height: 100%;
  border-radius: 0;
}

.modal-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #28B28B;
  border-bottom: 1px solid #e0e0e0;
  color: #ffffff;
  font-weight: 600;
  font-size: 18px;
  height: 49px;
  border-radius: 4px 4px 0 0;
  .icon_r{
    display: flex;
    align-items: center;
    justify-content: center;
    img{
      width: 24px;
      height: 24px;
    }
  }
  .closeIcon{
    margin-left: 16px;
  }

}
.fullscreen_btn{
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 18px;
  color: #000000;
  position: fixed;
  top:88px;
  right: 57px;
  img{
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}
.fullscreen_btn:hover{
  color: #28B28B;
}
.modal-body {

  padding: 16px;

}
.clockText{
  width: 100%;
  text-align: center;
  font-weight: 500;
  font-size: 18px;
  color: #333333;
  margin-bottom: 16px;
  margin-top: 20px;
}
.btn-container{
  width: 100%;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 0 80px;
  box-sizing: border-box;
}
.endBtn{
  padding: 5px 30px;
  box-sizing: border-box;
  background-color: #fff;
  border: 1px solid #bbbbbb;
  margin-right: 100px;
  border-radius: 8px;
}
.pauseBtn{
  padding: 5px 30px;
  box-sizing: border-box;
  background-color: #28B28B;
  color: #ffffff;
  border-radius: 8px;
}
.disabled{
  background-color: #c8c9cc;
}
.clock-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.colon {
  height: 50px;
  padding: 0 10px;
  display: flex;
  justify-content: space-around;
  flex-direction: column;

  &::after,
  &::before {
    content: '';
    display: block;
    width: 10px;
    height: 10px;
    background: #EEA74C;
    border-radius: 50%;
  }
}

.danger-color {
  &::after,
  &::before {
    background: red;
  }
}

.time-picker {
  display: flex;
  justify-content: space-between;
  color: #999999;
width: 100%;
  .column {
    width: calc(100% / 3);
    height: 120px;
    overflow-y: auto;
    position: relative;
  }

  .column::-webkit-scrollbar {
    display: none; /* 隐藏滚动条 */
  }

  .column::-webkit-scrollbar {
    width: 0; /* 隐藏滚动条 */
    background: transparent; /* 背景透明 */
  }

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
    text-align: center;
  }

  li {
    height: 40px;
    line-height: 40px;
    font-size: 18px;
  }

  .selected {
    background-color: #f1f1f1;
    color: black;
  }

}
.start_btn{
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 40px;
  div{
    width: 176px;
    height: 32px;
    line-height: 32px;
    font-weight: 500;
    font-size: 14px;
    color: #FFFFFF;
    text-align: center;
    background: #28B28B;
    border-radius: 8px;
  }
}
</style>

